package com.apes.autoparts.parts.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.parts.model.*;
import com.apes.autoparts.parts.repository.AutoModelRepository;
import com.apes.autoparts.parts.repository.MainGroupRepository;
import com.apes.autoparts.parts.repository.SubGroupImgRepository;
import com.apes.autoparts.parts.repository.SubGroupRepository;
import com.apes.autoparts.parts.util.FtpUtil;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

@Service("querySubGroupService")
public class QuerySubGroupService extends DomainService {

    @Autowired
    private ApiAutoParts91Service apiService;

    @Autowired
    private SubGroupRepository subGroupRepository;

    @Autowired
    private MainGroupRepository mainGroupRepository;

    @Autowired
    private AutoModelRepository autoModelRepository;

    @Autowired
    private SubGroupImgRepository subGroupImgRepository;

    @Autowired
    private QueryPartsService queryPartsService;

    @Autowired
    private SequenceService sequenceService;
    /****
     * TODO:
     * 1. 增加关键字查询
     * 2. 增加目录筛选
     */





    /***
     * 查询子组
     */

    public JSONArray querySubGroup(SimpleRequest request) {

        JSONObject param = request.getJO();
        //前端传过来的selectorId是车架号id


        JSONArray subGroupRepose = apiService.querySubGroup(param);

        if (subGroupRepose == null)
            subGroupRepose = new JSONArray();
        // 返回数据
        return subGroupRepose;



    }

    /***
     * 查询图片热点
     */
    public JSONObject queryImgPoint(SimpleRequest request) {
        JSONObject param = request.getJO();
        JSONObject response = apiService.queryHotPointsWithSubGroup(param);
        if (response == null)
            response = new JSONObject();
        return response;
    }

    /***
     * 查询图片热点
     */
    public List<SubGroupImg> queryImgPoint(JSONObject param, SubGroup subGroup) {
//        {
//            "vin":"LHGCP168288027506",
//                "brandCode":"honda",
//                "id":"3945",
//                "selectorId":"10135"
//        }
        JSONArray imgPointArray  = new JSONArray();
        param.put("id", subGroup.getSubGroupId());
        JSONObject response = apiService.queryHotPointsWithSubGroup(param);
        if (response != null)
            imgPointArray.add(response);

        return handleSubGroupImgResponse(imgPointArray);
    }



    /***
     * 处理子组返回数据
     */
    private List<SubGroup> handleSubGroupResponse(JSONArray subGroupRepose) {
        List<SubGroup> subGroupList = new ArrayList<>();
        if (subGroupRepose == null) return subGroupList;
        /***
         * 处理逻辑和返回数据
         */

        for (int i = 0; i < subGroupRepose.size(); i++) {

            //封装子组数据
            SubGroup subGroup = new SubGroup();
//                subGroup.setId(sequenceService.getId(SubGroup.CONST_TABLE_NAME));
            subGroup.setBelongTo(subGroupRepose.getJSONObject(i).getBoolean("belongTo"));
            subGroup.setCode(subGroupRepose.getJSONObject(i).getString("code"));
            subGroup.setImageSN(subGroupRepose.getJSONObject(i).getString("imageSN"));
            subGroup.setMainGroupCode(subGroupRepose.getJSONObject(i).getString("mainGroupCode"));
            String imageUrl = subGroupRepose.getJSONObject(i).getString("imageUrl");
            /**
             * 处理多图片地址
             */
            try {
                if ( imageUrl != null ) {
                    // 可能存在多个图片地址
                    String imageUrls = "";
                    if (imageUrl.contains(",")) {
                        String[] split = imageUrl.split(",");
                        for (int j = 0; j < split.length; j++) {
                            String img = apiService.saveImgToFtp(split[j]);
                            if (j + 1 >= split.length)
                                imageUrls += img;
                            else
                                imageUrls += img + ",";

                        }
                    }

                    subGroup.setOrgImageUrl(imageUrl);

                    if ( !"".equals(imageUrls) ) {
                        subGroup.setImageUrl(imageUrls);
                    }
                    else {
                        String imgToFtp = apiService.saveImgToFtp(imageUrl);
                        subGroup.setImageUrl(imgToFtp);
                    }
                }
            } catch (Exception e) {
                subGroup.setValid(false);
                subGroup.setNote("图片保存失败");
            }
            subGroup.setName(subGroupRepose.getJSONObject(i).getString("name"));
            subGroup.setRemark(subGroupRepose.getJSONObject(i).getString("remark"));
            subGroup.setApplicableModel(subGroupRepose.getJSONObject(i).getString("applicableModel"));
            subGroup.setSubGroupId(subGroupRepose.getJSONObject(i).getString("id"));
            subGroup.setDescription(subGroupRepose.getJSONObject(i).getString("description"));
            subGroup.setTimestamp(new Date());
            subGroupList.add(subGroup);



        }

        return subGroupList;
    }


    // 处理图片热点返回数据
    private List<SubGroupImg> handleSubGroupImgResponse(JSONArray param) {
        List<SubGroupImg> subGroupImgList = new ArrayList<>();
        if (param == null) return subGroupImgList;

        /***
         * 处理逻辑
         */
        for (int i = 0; i < param.size(); i++) {
            SubGroupImg subGroupImg = new SubGroupImg();

            // 处理图片的url
            String url = param.getJSONObject(i).getJSONArray("imgs").getJSONObject(0).getString("url");

            // 保存图片
            String imgUrl = null;
            if (url != null) {
                try {
                    imgUrl = apiService.saveImgToFtp(url);
                } catch (Exception e) {
                    subGroupImg.setValid(false);
                    subGroupImg.setNote("保存图片失败");
                }

            }


            JSONArray poins = param.getJSONObject(i).getJSONArray("imgs").getJSONObject(0).getJSONArray("points");

            //// 处理热点图数据
            List<SubGroupImgPoint> subGroupImgPointList = new ArrayList<>();
            for (int j = 0; j < poins.size(); j++) {
                SubGroupImgPoint subGroupImgPoint = new SubGroupImgPoint();
                subGroupImgPoint.setW(poins.getJSONObject(j).getString("w"));
                subGroupImgPoint.setX(poins.getJSONObject(j).getString("x"));
                subGroupImgPoint.setH(poins.getJSONObject(j).getString("h"));
                subGroupImgPoint.setY(poins.getJSONObject(j).getString("y"));
                subGroupImgPoint.setSn(poins.getJSONObject(j).getString("sn"));
                subGroupImgPoint.setTimestamp(new Date());
                subGroupImgPointList.add(subGroupImgPoint);

            }
            subGroupImg.setSubGroupImgPoints(subGroupImgPointList);
            subGroupImg.setOrgUrl(url);
            subGroupImg.setUrl(imgUrl);
            subGroupImg.setTimestamp(new Date());
            subGroupImgList.add(subGroupImg);
        }


        return subGroupImgList;
    }

    /***
     * 查询子组
     */

    public List<SubGroup> querySubGroupAll(SimpleRequest request) {

        JSONObject param = request.getJO();

        //前端传过来的selectorId是车架号id
        AutoModel autoModel = autoModelRepository.findOne(param.getString("selectorId"));

        // 确认是否已经被解析过
        List<SubGroup> subGroups = subGroupRepository.findAll(
                JpaDsl.toCriteriaByEq(
                        "mainGroupId.id", param.getString("id")
                )
        );
        MainGroup mainGroup = mainGroupRepository.findOne(param.getString("id"));
        if (subGroups.size() != 0) return subGroups;

        // 获取子组数据
        param.put("selectorId", autoModel.getSelectorId());
        param.put("id", mainGroup.getCode());
        JSONArray subGroupRepose = apiService.querySubGroup(param);

        //处理子组数据
        List<SubGroup> subGroupList = handleSubGroupResponse(subGroupRepose);


        int count = 0;

        //获取热点图数据
        for (int i = 0; i < subGroupList.size(); i++) {
            List<SubGroupImg> subGroupImgList = queryImgPoint(param, subGroupList.get(i));
            int finalI = i;
            subGroupImgList.forEach(subGroupImg -> {
                subGroupList.get(finalI).getSubGroupImgs().add(subGroupImg);
            });


        }

        // 保存子组数据
        subGroupList.forEach(subGroup -> {
            subGroup.setMainGroupId(mainGroup);
            subGroupRepository.saveAndFlush(subGroup);
        });



        // 获取配件
        JSONObject jo = request.getJO();
        AutoModel finalAutoModel = autoModel;
        subGroupList.forEach(subGroup -> {
            jo.put("id", subGroup.getId());
            jo.put("selectorId", autoModel.getId());
            request.setData(jo);

            queryPartsService.queryPartsAll(request);
        });
        return subGroupList;
    }

    public List<SubGroup> querySubGroupAll(JSONObject param) {



        JSONArray subGroupRepose = apiService.querySubGroup(param);
        //处理子组数据
        List<SubGroup> subGroupList = handleSubGroupResponse(subGroupRepose);


        return subGroupList;
    }
    /***
     * 查询图片热点
     */
    public List<SubGroupImg> queryImgPointAll(JSONObject param) {

        JSONArray imgPointArray  = new JSONArray();
        JSONObject response = apiService.queryHotPointsWithSubGroup(param);
        if (response != null)
            imgPointArray.add(response);
        List<SubGroup> list = subGroupRepository.findAll(JpaDsl.toCriteriaByEq(
                "subGroupId", param.getString("id"), "orgSelectorId.selectorId", param.getString("selectorId")
        ));

        List<SubGroupImg> subGroupImgs = handleSubGroupImgResponse(imgPointArray);
        return subGroupImgs;
    }



}
